Ext.define("DesktopService",{
	/**
	 * 初始化主题背景选择器的内容
	 * 
	 * @returns {String} 返回主题选择器的HTML内容
	 */
	initThemesHTML:function(){
		var html = "<div style='overflow:auto;background-color:white;height:400px;'>";
		var imgs = new Array("theme_2011.jpg", "theme_7_7.jpg", "theme_blue1.jpg",
				"theme_childhood.jpg", "theme_christmas.jpg", "theme_cloud.jpg",
				"theme_dandelionDream.jpg", "theme_dreamSky.jpg");
		var imgNote = new Array("欢庆元旦", "七夕", "幻彩蓝天", "童年记忆", "圣诞快乐", "晴空行云",
				"蒲英之梦", "梦翔天际");
		for ( var i = 0; i < imgs.length; i++) {
			var bgcolor = "";
			if (("bg_themeICON_" + i) == selectIMGID) {// 判断该主题是否被选中
				bgcolor = "background-color:#CBE7FC";
			}
			var imgNode = "<div style='width:150px;height:140px;float:left;margin-left:20px;margin-top:10px;cursor:pointer;"
					+ bgcolor
					+ "' class='bgMin' onclick='changeDesktopBg(\""
					+ imgs[i]
					+ "\",\"bg_themeICON_"
					+ i
					+ "\")' id='bg_themeICON_"
					+ i + "'>";
			imgNode += "<img style='width:140px;height:110px;padding-left:8px;padding-top:10px;' src='img/bg/icon/"
					+ imgs[i]
					+ "'/><span style='display:block;width:150px;height:20px;padding-top:5px;text-align:center;'>"
					+ imgNote[i] + "</span>";
			imgNode += "</div>";
			html += imgNode;
		}
		html += "</div>";
		return html;
	},
	/**
	 * 初始化桌面右键菜单
	 * 
	 * @returns {Ext.menu.Menu}
	 */
	initDesMenu:function(){
		var menu = new Ext.menu.Menu();
		menu.add({
			id : 'showDesktop',
			text : '显示桌面',
			iconCls : "icon-desktop",
			handler : App.showDesktopHandler
		});
		menu.add({
			id : 'themesSetting',
			text : '主题设置',
			iconCls : "icon-themesetting",
			handler : App.themeSettingHandler
		});
		menu.add({
			id : 'sysSetting',
			text : '系统设置',
			iconCls : "icon-setting",
			handler : App.sysSettingHandler
		});
		return menu;
	},
	/**
	 * 初始化询问导航栏的右键菜单
	 * 
	 * @returns {Ext.menu.Menu}
	 */
	initNavMenu:function(){
		var menu = new Ext.menu.Menu();
		menu.add({
			id : 'test',
			text : '显示桌面',
			iconCls : "icon-desktop",
			handler : App.showDesktopHandler
		});
		return menu;
	},
	/**
	 * 初始化桌面应用
	 */
	initApp:function(){
		CMPFactory.createAppICON("app_login",10,10,"./img/app/Bettle.png",function(){alert("----")});
		CMPFactory.createAppICON("app_login",10,70,"./img/app/Bettle.png",function(){alert("----")});
	},
	showLoginWindow:function(){
		var loginTop=60;
		var loginLeft=30;
		var loginWinItems = [
			CMPFactory.createLabel(null,"帐&nbsp;&nbsp;&nbsp;号",14,loginLeft,loginTop+3),
			CMPFactory.createTextfield("uid","uid","text",loginLeft+50,loginTop,180,27,/^\d+$/,"UID"),
		  	CMPFactory.createLabel(null,"密&nbsp;&nbsp;&nbsp;码",14,loginLeft,loginTop+38),
		  	CMPFactory.createTextfield("password","password","password",loginLeft+50,loginTop+35,180,27,null,"登录密码"),
		  	CMPFactory.createLabel(null,"<span style='color:#0486DE;cursor:pointer' title='注册帐号'>注册帐号</span>",13,loginLeft+240,loginTop+5,LoginWinHandlers.regis),
		  	CMPFactory.createLabel(null,"<span style='color:#0486DE;cursor:pointer' title='忘记密码'>忘记密码</span>",13,loginLeft+240,loginTop+40,LoginWinHandlers.forgetPassword),
		  	CMPFactory.createLabel(null,"登录状态",12,loginLeft,loginTop+80),
		  	new StatusLabel({id:"LoginWinStatusLabel",x:loginLeft+55,y:loginTop+80,width:50,height:20,listeners:{click:{element:"el",fn:LoginWinHandlers.statusHandler}}}),
		  	CMPFactory.createCheckbox("记住密码",loginLeft+150,loginTop+80,true),
		  	CMPFactory.createCheckbox("自动登录",loginLeft+230,loginTop+80,false),
		  	CMPFactory.createLabel("noticeLabel","",13,loginLeft,loginTop+95),
		  	CMPFactory.createButton("登&nbsp;录","loginBt","",360-90*2,250-60,80,26,LoginWinHandlers.login),
		  	CMPFactory.createButton("设&nbsp;置","configBt","icon-setting",360-90,250-60,80,26,null)
		];
		CMPFactory.createQQStyleWindow("loginWindow",(AppContext.desktopWidth-360)/2,(AppContext.desktopHeight-250)/2,360,250,loginWinItems,"img/tool/connect.png","登录",false,[false,false,true]).show();//[null,null,loginCloseHandler]
	},
	showListWindow:function(){
		var listItems = [
		     CMPFactory.createContainer("selfMessCtn",0,0,"auto",70,"",null,"absolute"),
		     CMPFactory.createContainer("friendsPanel",0,70,"auto",500-90,"",[{xtype:"label",x:0,y:(500-90)/3,width:300,html:"<div style='width:100%;text-align:center;'>正在登录...<br/><br/><img src='./img/tool/loading.gif' style='width:130px;'/></div>"}],"absolute")
		];
		var win = CMPFactory.createQQStyleWindow("listWindow",AppContext.listWinX,AppContext.listWinY,AppContext.listWinWidth,AppContext.listWinHeight,listItems,"","好友列表",false,[true,false,true],[null,null,ListWindowHandler.close]);
		win.addListener("destroy",function(e){Ext.getCmp("desktop").getTaskBar().removeTrayBar("listWindow")});
		win.show();
	},
	openBrowser:function(url,title,width,height,scroll,min,max,resize){
		var id= new Date().getTime()+"-browser";
		var win = CMPFactory.createQQStyleWindow(id,(AppContext.desktopWidth-width)/2,(AppContext.desktopHeight-height)/2,width,height,[],"img/tool/browser.png",title,resize,[min,max,true]);
		win.show();
		if(url.lastIndexOf("?")!=-1){
			url+="&t="+new Date().getTime()+"&bid="+id;
		}else{
			url+="?t="+new Date().getTime()+"&bid="+id;
		}
		win.getBody().setAutoScroll(scroll);
		var overflow = scroll?"auto":"hidden";
		win.getBody().update("<iframe src='"+url+"' style='border:none;overflow:"+overflow+";width:"+(width-7)+"px;height:"+(height-25)+"px;'/>",false);
		console.log(Ext.get("iframe"));
		console.log("------");
		//new Ext.container.Container({x:5,y:5,width:590,height:370,html:"<iframe src='"+url+"' style='border:0px;overflow:auto;width:100%;height:100%;'/>"})
	},
	statics:{
		resizeBody:function(w,h){
			Ext.getCmp("desktop").setSize(w,h);
			AppContext.screenWidth = Ext.getDoc().getViewSize().width//当页面大小更改的时候应该将context中的参数更改
			AppContext.screenHeight = h;
			AppContext.desktopWidth = AppContext.screenWidth;
			AppContext.desktopHeight = AppContext.screenHeight-37;
		}
	}
});

/**
 * 用户相关处理的服务类
 */
Ext.define("UserService",{
	/**
	 * 加载好友
	 */
	loadFriends:function(){
		Ext.Ajax.request({
			url:"servlet/SelfMessage.do",
			method:"post",
			params:{
				uid:AppContext.getUID()
			},
			success:function(response,opts){
				var user;
				try{
					user = Ext.JSON.decode(response.responseText);
				}catch(msg){
					Ext.Msg.alert("错误","转换数据类型失败!");
					return;
				}
				if(typeof user!="object"){
					Ext.Msg.alert("错误","服务返回数据错误!");
				}else{
					AppContext.setNickname(user.nickname);
					AppContext.setICON(user.icon);
					Ext.getCmp("selfMessCtn").add({xtype:"label",x:10,y:10,width:40,height:40,html:"<img src='./img/info/"+user.icon+".jpg' style='width:40px;height:40px;border:1px solid #0486DE;cursor:pointer;'/>"});
					Ext.getCmp("selfMessCtn").add(new StatusLabel({id:"ListWinStatusLabel",x:60,y:10,width:50,height:20,status:Ext.getCmp("LoginWinStatusLabel").status,listeners:{click:{element:"el",fn:ListWindowHandler.statusHandler}}}));
					Ext.getCmp("selfMessCtn").add({xtype:"label",x:110,y:10,width:80,height:20,html:user.nickname.ellipsis(10)});
					Ext.getCmp("selfMessCtn").add({xtype:"label",x:60,y:30,width:Ext.getCmp("listWindow").getWidth()-60-10,height:20,html:user.signature.ellipsis(30)});
					var body =Ext.getCmp("friendsPanel");
					var header = Ext.getCmp("selfMessCtn");
					body.removeAll(true);//移除其中的组件
					body.setHeight(body.getHeight()-50);//将中间部分高度减少50
					//下面是添加正在拉取提示
					var tools = [
						CMPFactory.createButtonLabel("",10,20,"设置","icon-setting",App.sysSettingHandler),
						CMPFactory.createButtonLabel("",60,20,"查找","icon-search",ListWindowHandler.searchFriend)
					];
					var footer = CMPFactory.createContainer(Ext.getCmp("listWindow").id+"_footer",0,Ext.getCmp("listWindow").getHeight()-50,"auto",50,"",tools,"absolute",{backgroundColor:"white"});
					Ext.getCmp("listWindow").add(footer);
					body.add({id:"friendPanBody",xtype:"label",x:0,y:(body.getHeight()-50)/3,width:body.getWidth(),height:100});
					Ext.getCmp("friendPanBody").setText("<div style='width:100%;text-align:center;'>正在拉取好友列表...<br/><br/><img src='./img/tool/loading.gif' style='width:130px;'/></div>", false);
					var tree = new ZTree({
						url:"servlet/LoadGroup.do?uid="+AppContext.getUID(),
						childUrl:"servlet/LoadFriends.do",
						method:"post"
					});
					body.setAutoScroll(true);
					tree.loadGroup(body,"",0,0,body.getWidth()-30);
					Ext.getCmp("desktop").getTaskBar().addTrayBar(Ext.getCmp("listWindow"),"img/app/Bettle.png",ListWindowHandler.click);
				}
			}
		});
	},
	/**
	 * 更新自己状态 
	 */
	updateStatus:function(status){
		var id  = Ext.getCmp("selfMessCtn").query("label")[0].id;
		Ext.getCmp(id).update("<img src='./img/info/"+AppContext.getICON()+"_h.jpg' style='width:40px;height:40px;border:1px solid #0486DE;cursor:pointer;'/>");;
	}
});

/**
 * 消息服务类
 */
Ext.define("MessageService",{
	/**
	 * 加载历史记录
	 * @param {Ext.form.Label} win 历史记录显示面板
	 * @param {int} fid 好友ID
	 * @param {days} days 需要查询历史记录的天数
	 */
	loadHistory:function(win,fid,days){
		Ext.Ajax.request({
			url:"servlet/LoadHistory.do",
			params:{
				uid:AppContext.getUID(),
				fid:fid,
				days:days
			},
			method:"post",
			success:function(response,opts){
				var res = response.responseText;
				var data = null;
				try{
					data = Ext.JSON.decode(res);
				}catch(msg){
					win.update("获取历史记录失败，请重试!");
					return;
				}
				if(data.length==0){
					win.update("与该好友不存在聊天记录!");
					return;
				}
				var msg = "";
				var service = new MessageHandleService();
				for(var i=0;i<data.length;i++){
					msg+="<div style='padding-top:5px;'>&nbsp;日期:"+data[i]["date"]+"</div><div>--------------------------------------</div>";
					var his = data[i]["history"];//获取的是某一天所有的聊天记录
					for(var j=0;j<his.length;j++){
						if(his[j]["from"]==AppContext.getUID()){//自己发出的消息
							msg+=service.formatSendMsg(his[j]["time"],his[j]["msg"]);
						}else{
							msg+=service.formatMsg(his[j]["from"],his[j]["time"],his[j]["msg"]);
						}
					}
				}
				win.update(msg);
			}
		});
	},
	statics:{
		/**
		 * 检测对某一用户是否可以抖动，可以返回true，反之返回false
		 */
		canShake:function(id){
			if(this.shakes==null||this.shakes=="undefined"){
				this.shakes = new Ext.util.HashMap();
			}
			var last = this.shakes.get(id);
			if(last==undefined){
				this.shakes.add(id,(new Date()-0));
				return true;
			}
			if((new Date()-last)>(10*1000)){//如果抖动时间与当前时间相隔不越过30S,则禁止再次抖动
				this.shakes.replace(id,(new Date()-0))
				return true;
			}
			return false;
			
		},
		/**
		 * 播放收到消息的提示声
		 */
		playReviceMusic:function(){
			document.getElementById("audioNode").src="music/msg.mp3";
			Media = document.getElementById("audioNode");
			Media.play();
		},
		/**
		 *播放抖动声音 
		 */
		playShakeMusic:function(){
			document.getElementById("audioNode").src="music/shake.mp3";
			Media = document.getElementById("audioNode");
			Media.play();
		}
	},
	/**
	 * 当收到消息时使任务栏中的任务闪烁
	 * @param {String} id 任务栏中DIV的ID
	 *TODO 需要修改
	 */
	blinkJob:function(id){
		var i=0,runner = new Ext.util.TaskRunner();
		var task = {
			    run: function(){
			    	if(i%2==0){
			    		document.getElementById(id).style.background='yellow';
			    	}else{
			    		document.getElementById(id).style.background="-webkit-linear-gradient(#fff,#A6A6A5)";
			    	}
			    	i++;
			    	if(i>=10){//5S后停止闪烁
			    		document.getElementById(id).style.background="-webkit-linear-gradient(#fff,#A6A6A5)";
			    		runner.stop(task);
			    	}
			    },
			    interval: 500
			}
		var runner = new Ext.util.TaskRunner();
		runner.start(task);
	}
});
